package com.example.yangxueqin

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.view.MenuItem
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.io.File

class MainActivity : AppCompatActivity() {

    private lateinit var minEditText: EditText
    private lateinit var maxEditText: EditText
    private lateinit var startButton: Button
    private lateinit var stopButton: Button
    private lateinit var resultListView: ListView
    private lateinit var totalPrimesTextView: TextView
    private var isCalculating = false
    private val handler = Handler(Looper.getMainLooper())
    private val primeNumbers = mutableListOf<Int>()
    private lateinit var adapter: ArrayAdapter<Int>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        minEditText = findViewById(R.id.minEditText)
        maxEditText = findViewById(R.id.maxEditText)
        startButton = findViewById(R.id.startButton)
        stopButton = findViewById(R.id.stopButton)
        resultListView = findViewById(R.id.resultListView)
        totalPrimesTextView = findViewById(R.id.totalPrimesTextView)

        adapter = ArrayAdapter(this, R.layout.list_item, primeNumbers)
        resultListView.adapter = adapter

        startButton.setOnClickListener {
            val min = minEditText.text.toString().toInt()
            val max = maxEditText.text.toString().toInt()
            startPrimeCalculation(min, max)
        }

        stopButton.setOnClickListener {
            isCalculating = false
        }

        loadHistory()
    }

    private fun startPrimeCalculation(min: Int, max: Int) {
        isCalculating = true
        primeNumbers.clear()
        adapter.notifyDataSetChanged()
        Thread {
            for (i in min..max) {
                if (!isCalculating) break
                if (isPrime(i)) {
                    primeNumbers.add(i)
                    handler.post {
                        adapter.notifyDataSetChanged()
                        totalPrimesTextView.text = "Total primes: ${primeNumbers.size}"
                    }
                }
            }
            saveHistory()
        }.start()
    }

    private fun isPrime(num: Int): Boolean {
        if (num < 2) return false
        for (i in 2..Math.sqrt(num.toDouble()).toInt()) {
            if (num % i == 0) return false
        }
        return true
    }

    private fun saveHistory() {
        val file = File(filesDir, "history.txt")
        file.writeText(primeNumbers.joinToString(","))
    }

    private fun loadHistory() {
        val file = File(filesDir, "history.txt")
        if (file.exists()) {
            val content = file.readText()
            val numbers = content.split(",").map { it.toInt() }
            primeNumbers.addAll(numbers)
            adapter.notifyDataSetChanged()
            totalPrimesTextView.text = "Total primes: ${primeNumbers.size}"
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.historyMenuItem -> {
                startActivity(Intent(this, HistoryActivity::class.java))
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}